﻿using System;
using System.Xml;

namespace Utility
{
    public static class ConfigHelper
    {
        public static string GetConfig(string key)
        {
            return System.Configuration.ConfigurationManager.AppSettings[key];
        }

        public static void SetConfig(string key, string value)
        {
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save(System.Configuration.ConfigurationSaveMode.Modified);
            System.Configuration.ConfigurationManager.RefreshSection("appSettings");
        }
    }

    public class SysConfig : XmlDocument
    {

        private static SysConfig instance = new SysConfig();
        public static SysConfig GetInstance()
        {
            return instance;
        }
        private SysConfig()
        {
            try
            {
                Load(Environment.CurrentDirectory + "\\SysConfig.xml");
            }
            catch (Exception ex)
            {
                return;
            }
        }

        public string GetAttributeValue(string path, string attributeName)
        {
            try
            {
                var node = SelectSingleNode(path);
                if (node != null && node is XmlElement)
                {
                    var element = (XmlElement)node;
                    return element.GetAttribute(attributeName);
                }
                else
                {
                    Logger.Warn($"Sysconfig配置文件未找到路径为 '{path}' 的元素或元素不是XmlElement类型");
                }
            }
            catch (Exception ex)
            {
                Logger.Warn($"Sysconfig配置文件获取属性值失败：{ex.Message}");
            }

            return null;
        }
    }
}
